<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>06_事件总线-事件总线的实现</title>
</head>

<body>

  <button class="event-bus">事件总线(event-bus)</button>

  <script>
    // 事件总线EventBus类
    class EventBus {
      constructor() {
        this.eventMap = {}
      }

      emit(eventName, ...args) {
        let eventFns = this.eventMap[eventName]
        if (!eventFns) return
        eventFns.forEach(fn => {
          fn(...args)
        });
      }

      on(eventName, callback) {
        let eventFns = this.eventMap[eventName]
        if (!eventFns) {
          eventFns = []
          this.eventMap[eventName] = eventFns
        }
        eventFns.push(callback)
      }

      off(eventName, callback) {
        let eventFns = this.eventMap[eventName]

        if (!eventFns) return
        // this.eventMap[eventName] = eventFns.filter(fn => fn !== callback)

        let index = 0
        for (const item of eventFns) {
          index = eventFns.indexOf(callback)
          if (index !== -1) {
            eventFns.splice(index, 1)
            break;
          }
        }

        if (eventFns.length === 0) {
          delete this.eventMap[eventName]
        }
      }
    }

    const eventBus = new EventBus()

    function handleClick(name, obj) {
      console.log("navClick listener 01", name, obj)
    }

    eventBus.on("navClick", (name, obj) => {
      console.log("navClick listener 01", name, obj)
    })

    eventBus.on("navClick", handleClick)

    setTimeout(() => {
      eventBus.off("navClick", handleClick)
    }, 2000)

    const btn = document.querySelector('.event-bus')
    btn.onclick = () => {
      console.log("按钮被点击了");

      eventBus.emit("navClick", "导航被点击了", { a: 1, b: 2 })
    }

  </script>

</body>

</html>